/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rw.magallanes.ide.main;

import com.rw.magallanes.core.Category;
import com.rw.magallanes.core.Item;
import com.rw.magallanes.core.Warehouse;
import com.rw.magallanes.db.StorageException;
import com.rw.magallanes.ide.action.AddCategoryAction;
import com.rw.magallanes.ide.action.AddItemAction;
import com.rw.magallanes.ide.action.ChangeCategoryAction;
import com.rw.magallanes.ide.action.DeleteCategoryAction;
import com.rw.magallanes.ide.action.DeleteItemAction;
import com.rw.magallanes.ide.action.RenameCategoryAction;
import com.rw.magallanes.ide.action.SaveAction;
import com.rw.magallanes.ide.action.SearchAction;
import com.rw.magallanes.utilities.MessageType;
import com.rw.magallanes.utilities.Utilities;
import com.rw.table.EditionStyle;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.ListModel;
import javax.swing.event.ListDataListener;

/**
 *
 * @author Gonzalez
 */
public class MainFrame extends javax.swing.JFrame {

    private Warehouse wh;
    private ItemTableModel modelItems;

    public MainFrame(Warehouse wh) {
        this.wh = wh;
        initComponents();
        initValues();
    }

    private void initValues() {
        this.setTitle("Sistema de Administracion");
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                close();
            }
        });


        this.listCategories.setModel(new ListModel() {
            @Override
            public int getSize() {
                return wh.getCategories().size();
            }

            @Override
            public Object getElementAt(int index) {
                return wh.getCategories().get(index);
            }

            @Override
            public void addListDataListener(ListDataListener l) {
            }

            @Override
            public void removeListDataListener(ListDataListener l) {
            }
        });

        // Acciones
        AddItemAction addItemAction = new AddItemAction();
        DeleteItemAction deleteItemAction = new DeleteItemAction();
        ChangeCategoryAction changeCategoryAction = new ChangeCategoryAction();
        AddCategoryAction addCategoryAction = new AddCategoryAction();
        DeleteCategoryAction deleteCategoryAction = new DeleteCategoryAction();
        SearchAction searchAction = new SearchAction();
        SaveAction saveAction = new SaveAction();
        RenameCategoryAction renameCategoryAction = new RenameCategoryAction();

        // Lista
        JPopupMenu popupList = new JPopupMenu();
        popupList.add(renameCategoryAction);
        this.listCategories.setComponentPopupMenu(popupList);

        if (wh.getCategories().size() > 0) {
            this.listCategories.setSelectedIndex(0);
            this.listCategories.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    Category selectedCategory = getSelectedCategory();
                    if (selectedCategory != null) {
                        updateItemsFor(selectedCategory);
                    }
                }
            });
        }

        // Tabla
        this.modelItems = new ItemTableModel();
        this.tableItems.setModel(modelItems);
        this.modelItems.configure(tableItems, EditionStyle.EXCEL_STYLE);

        JPopupMenu popupTable = new JPopupMenu();
        popupTable.add(deleteItemAction);
        popupTable.add(changeCategoryAction);
        this.tableItems.setComponentPopupMenu(popupTable);

        this.buttonAddItem.setAction(addItemAction);
        this.buttonDeleteItem.setAction(deleteItemAction);
        this.buttonAddCategory.setAction(addCategoryAction);
        this.buttonDeleteCategory.setAction(deleteCategoryAction);

        this.buttonAddItem.setText("+");
        this.buttonDeleteItem.setText("-");
        this.buttonAddCategory.setText("+");
        this.buttonDeleteCategory.setText("-");

        this.menuitemSave.setAction(saveAction);
        this.menuitemSearch.setAction(searchAction);

        JPanel main = (JPanel) this.getContentPane();
        Utilities.configureAction(main, saveAction);
        Utilities.configureAction(main, searchAction);
    }

    public void showMe() {
        this.setSize(800, 600);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    private void close() {
        try {
            wh.save();
        } catch (StorageException ex) {
            Utilities.showMsg(this, "Error al guardar la base de datos", MessageType.ERROR);
        }
        this.dispose();
    }

    public Warehouse getWarehouse() {
        return wh;
    }

    public void stopEditingItemsTable() {
        this.tableItems.getDefaultEditor(Object.class).stopCellEditing();
    }

    public void updateItemsFor(Category category) {
        if (category != null) {
            this.modelItems.setItems(category.getItems());
        } else {
            this.modelItems.setItems(null);
        }

        this.modelItems.fireTableDataChanged();
    }

    public void updateCategoriesTable() {
        this.listCategories.updateUI();
    }

    public Item getSelectedItem() {
        int row = this.tableItems.getSelectedRow();
        if (row >= 0) {
            return modelItems.getItem(row);
        }
        return null;
    }

    public Category getSelectedCategory() {
        Object selectedValue = this.listCategories.getSelectedValue();
        if (selectedValue != null) {
            return (Category) selectedValue;
        }
        return null;
    }

    public void selectItemInTable(Item item) {
        Category category = item.getCategory();
        int index = category.getItems().indexOf(item);

        this.tableItems.setRowSelectionInterval(index, index);
        this.tableItems.setColumnSelectionInterval(0, 0);

        Rectangle r = this.tableItems.getCellRect(index, 0, false);
        this.tableItems.scrollRectToVisible(r);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        splitCenter = new javax.swing.JSplitPane();
        panelCategories = new javax.swing.JPanel();
        scrollCategories = new javax.swing.JScrollPane();
        listCategories = new javax.swing.JList();
        panelCategoryButtons = new javax.swing.JPanel();
        buttonAddCategory = new javax.swing.JButton();
        buttonDeleteCategory = new javax.swing.JButton();
        panelItems = new javax.swing.JPanel();
        panelTableItems = new javax.swing.JPanel();
        scrollTableItems = new javax.swing.JScrollPane();
        tableItems = new javax.swing.JTable();
        panelTableItemsButtons = new javax.swing.JPanel();
        buttonAddItem = new javax.swing.JButton();
        buttonDeleteItem = new javax.swing.JButton();
        menubar = new javax.swing.JMenuBar();
        menu = new javax.swing.JMenu();
        menuitemSave = new javax.swing.JMenuItem();
        menuitemClose = new javax.swing.JMenuItem();
        menuTools = new javax.swing.JMenu();
        menuitemSearch = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        splitCenter.setDividerLocation(200);

        panelCategories.setBorder(javax.swing.BorderFactory.createTitledBorder("Categorias"));
        panelCategories.setLayout(new java.awt.BorderLayout());

        listCategories.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        scrollCategories.setViewportView(listCategories);

        panelCategories.add(scrollCategories, java.awt.BorderLayout.CENTER);

        panelCategoryButtons.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        buttonAddCategory.setText("+");
        panelCategoryButtons.add(buttonAddCategory);

        buttonDeleteCategory.setText("-");
        buttonDeleteCategory.setMaximumSize(new java.awt.Dimension(41, 23));
        buttonDeleteCategory.setMinimumSize(new java.awt.Dimension(41, 23));
        buttonDeleteCategory.setPreferredSize(new java.awt.Dimension(41, 23));
        panelCategoryButtons.add(buttonDeleteCategory);

        panelCategories.add(panelCategoryButtons, java.awt.BorderLayout.SOUTH);

        splitCenter.setLeftComponent(panelCategories);

        panelItems.setBorder(javax.swing.BorderFactory.createTitledBorder("Items"));
        panelItems.setLayout(new java.awt.BorderLayout());

        panelTableItems.setLayout(new javax.swing.BoxLayout(panelTableItems, javax.swing.BoxLayout.LINE_AXIS));

        tableItems.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        scrollTableItems.setViewportView(tableItems);

        panelTableItems.add(scrollTableItems);

        panelItems.add(panelTableItems, java.awt.BorderLayout.CENTER);

        panelTableItemsButtons.setLayout(new javax.swing.BoxLayout(panelTableItemsButtons, javax.swing.BoxLayout.Y_AXIS));

        buttonAddItem.setText("+");
        panelTableItemsButtons.add(buttonAddItem);

        buttonDeleteItem.setText("-");
        buttonDeleteItem.setMaximumSize(new java.awt.Dimension(41, 23));
        buttonDeleteItem.setMinimumSize(new java.awt.Dimension(41, 23));
        buttonDeleteItem.setPreferredSize(new java.awt.Dimension(41, 23));
        panelTableItemsButtons.add(buttonDeleteItem);

        panelItems.add(panelTableItemsButtons, java.awt.BorderLayout.EAST);

        splitCenter.setRightComponent(panelItems);

        getContentPane().add(splitCenter, java.awt.BorderLayout.CENTER);

        menu.setText("Archivo");

        menuitemSave.setText("Guardar");
        menuitemSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuitemSaveActionPerformed(evt);
            }
        });
        menu.add(menuitemSave);

        menuitemClose.setText("Cerrar");
        menuitemClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuitemCloseActionPerformed(evt);
            }
        });
        menu.add(menuitemClose);

        menubar.add(menu);

        menuTools.setText("Herramientas");

        menuitemSearch.setText("Buscar");
        menuitemSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuitemSearchActionPerformed(evt);
            }
        });
        menuTools.add(menuitemSearch);

        menubar.add(menuTools);

        setJMenuBar(menubar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void menuitemCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitemCloseActionPerformed
        close();
    }//GEN-LAST:event_menuitemCloseActionPerformed

    private void menuitemSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitemSearchActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_menuitemSearchActionPerformed

    private void menuitemSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuitemSaveActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_menuitemSaveActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAddCategory;
    private javax.swing.JButton buttonAddItem;
    private javax.swing.JButton buttonDeleteCategory;
    private javax.swing.JButton buttonDeleteItem;
    private javax.swing.JList listCategories;
    private javax.swing.JMenu menu;
    private javax.swing.JMenu menuTools;
    private javax.swing.JMenuBar menubar;
    private javax.swing.JMenuItem menuitemClose;
    private javax.swing.JMenuItem menuitemSave;
    private javax.swing.JMenuItem menuitemSearch;
    private javax.swing.JPanel panelCategories;
    private javax.swing.JPanel panelCategoryButtons;
    private javax.swing.JPanel panelItems;
    private javax.swing.JPanel panelTableItems;
    private javax.swing.JPanel panelTableItemsButtons;
    private javax.swing.JScrollPane scrollCategories;
    private javax.swing.JScrollPane scrollTableItems;
    private javax.swing.JSplitPane splitCenter;
    private javax.swing.JTable tableItems;
    // End of variables declaration//GEN-END:variables
}
